const Message = require('../models/Message');
const { query } = require('../config/mysqlConfig');
const User = require('../models/User');

// 发送群组消息
const sendGroupMessage = async (senderId, groupId, content, type = 'text') => {
  try {
    console.log(`尝试发送群组消息 - 用户: ${senderId}, 群组: ${groupId}`);

    // 检查群组是否存在且未解散
    const groupInfo = await query(
      'SELECT status FROM `groups` WHERE id = ?',
      [groupId]
    );

    if (groupInfo.length === 0) {
      throw new Error('群组不存在');
    }

    if (groupInfo[0].status === 'disbanded') {
      throw new Error('群组已解散，无法发送消息');
    }

    // 验证发送者是否为群组成员
    const membership = await query(
      'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, senderId]
    );

    console.log(`查询到的群组成员资格: ${JSON.stringify(membership)}`);

    if (membership.length === 0) {
      throw new Error('您不是该群组的成员，无法发送消息');
    }

    // 创建群组消息
    const message = await Message.create({
      sender: senderId,
      group_id: groupId,
      target_type: 'group',
      content,
      type,
      read_by: [senderId] // 发送者默认已读
    });

    console.log(`创建的消息ID: ${message._id}`);

    // 获取发送者详细信息
    const populatedMessage = await message.populate('sender', 'username avatar');

    // 格式化返回的消息，使其与前端接口一致
    const formattedMessage = {
      id: populatedMessage._id,
      group_id: groupId,
      sender: {
        id: populatedMessage.sender._id,
        username: populatedMessage.sender.username,
        avatar: populatedMessage.sender.avatar
      },
      content: populatedMessage.content,
      type: populatedMessage.type,
      created_at: populatedMessage.createdAt,
      updated_at: populatedMessage.updatedAt
    };

    return formattedMessage;
  } catch (error) {
    console.error('发送群组消息失败:', error);
    throw error;
  }
};

// 获取群组消息
const getGroupMessages = async (groupId, userId) => {
  try {
    console.log(`尝试获取群组消息 - 群组: ${groupId}, 用户: ${userId}`);

    // 验证用户是否为群组成员或曾经是群组成员
    const membership = await query(
      'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, userId]
    );

    console.log(`查询到的群组成员资格: ${JSON.stringify(membership)}`);

    if (membership.length === 0) {
      // 检查是否曾经是群组成员（通过历史消息判断）
      const hasHistoryMessages = await Message.countDocuments({
        group_id: groupId,
        target_type: 'group',
        sender: userId
      });

      if (hasHistoryMessages === 0) {
        throw new Error('您无权查看该群组的消息');
      }

      console.log(`用户 ${userId} 曾经是群组 ${groupId} 的成员，允许查看历史消息`);
    }

    // 获取群组消息
    const messages = await Message.find({
      group_id: groupId,
      target_type: 'group'
    })
      .sort({ createdAt: 1 })
      .populate('sender', 'username avatar');

    console.log(`找到 ${messages.length} 条群组消息`);

    // 只有当前群成员才能标记消息为已读
    if (membership.length > 0) {
      await Message.updateMany(
        {
          group_id: groupId,
          target_type: 'group',
          read_by: { $ne: userId }
        },
        { $addToSet: { read_by: userId } }
      );
      console.log('已将0条群组消息标记为已读');
    } else {
      console.log('用户已退出群组，跳过标记已读操作');
    }

    // 格式化消息以匹配前端接口
    const formattedMessages = messages.map(msg => ({
      id: msg._id,
      group_id: groupId,
      sender: {
        id: msg.sender._id,
        username: msg.sender.username,
        avatar: msg.sender.avatar
      },
      content: msg.content,
      type: msg.type,
      created_at: msg.createdAt,
      updated_at: msg.updatedAt
    }));

    return formattedMessages;
  } catch (error) {
    console.error('获取群组消息失败:', error);
    throw error;
  }
};

// 获取群组未读消息数量
const getGroupUnreadCount = async (groupId, userId) => {
  try {
    // 验证用户是否为群组成员
    const membership = await query(
      'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, userId]
    );

    if (membership.length === 0) {
      throw new Error('您不是该群组的成员');
    }

    // 计算未读消息数量（不包括自己发送的消息）
    const unreadCount = await Message.countDocuments({
      group_id: groupId,
      target_type: 'group',
      sender: { $ne: userId },
      read_by: { $ne: userId }
    });

    return unreadCount;
  } catch (error) {
    console.error('获取群组未读消息数量失败:', error);
    throw error;
  }
};

// 获取所有用户群组的未读消息状态
const getAllGroupsUnreadStatus = async (userId) => {
  try {
    // 获取用户所在的所有群组
    const groups = await query(
      'SELECT group_id FROM group_members WHERE user_id = ?',
      [userId]
    );

    // 如果用户没有加入任何群组，返回空数组
    if (groups.length === 0) {
      return [];
    }

    const groupIds = groups.map(g => g.group_id);
    const result = [];

    // 对每个群组计算未读消息数量
    for (const groupId of groupIds) {
      const unreadCount = await Message.countDocuments({
        group_id: groupId,
        target_type: 'group',
        sender: { $ne: userId },
        read_by: { $ne: userId }
      });

      // 获取群组信息
      const groupInfo = await query('SELECT * FROM `groups` WHERE id = ?', [groupId]);

      if (groupInfo.length > 0) {
        // 获取最后一条消息
        const lastMessage = await Message.findOne({
          group_id: groupId,
          target_type: 'group'
        })
          .sort({ createdAt: -1 })
          .populate('sender', 'username');

        result.push({
          group_id: groupId,
          name: groupInfo[0].name,
          group_avatar: groupInfo[0].group_avatar,
          unread_count: unreadCount,
          last_message: lastMessage
            ? {
                content: lastMessage.content,
                sender_name: lastMessage.sender.username,
                created_at: lastMessage.createdAt,
                type: lastMessage.type
              }
            : null
        });
      }
    }

    return result;
  } catch (error) {
    console.error('获取群组未读状态失败:', error);
    throw error;
  }
};

// 搜索群组消息
const searchGroupMessages = async (groupId, userId, keyword) => {
  try {
    console.log(`搜索群组消息 - 群组: ${groupId}, 用户: ${userId}, 关键词: "${keyword}"`);
    
    // 检查用户是否为当前群组成员
    const membership = await query(
      'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, userId]
    );

    const isCurrentMember = membership.length > 0;
    console.log(`用户是否为当前群成员: ${isCurrentMember}`);

    if (!isCurrentMember) {
      // 检查用户是否曾经是群组成员（通过历史消息判断）
      const historicalMessage = await Message.findOne({
        group_id: groupId,
        target_type: 'group',
        sender: userId
      });

      if (!historicalMessage) {
        throw new Error('您不是该群组的成员，无法搜索消息');
      }

      console.log(`用户 ${userId} 曾经是群组 ${groupId} 的成员，允许搜索历史消息`);
    }

    // 创建安全的正则表达式
    const safeKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const searchRegex = new RegExp(safeKeyword, 'i');

    // 搜索消息
    const messages = await Message.find({
      group_id: groupId,
      target_type: 'group',
      content: { $regex: searchRegex }
    })
      .sort({ createdAt: -1 })
      .populate('sender', 'username avatar');

    console.log(`找到 ${messages.length} 条匹配的群组消息`);

    // 格式化消息以匹配前端接口
    const formattedMessages = messages.map(msg => ({
      id: msg._id,
      _id: msg._id, // 同时提供id和_id以兼容前端
      group_id: groupId,
      sender: {
        id: msg.sender._id,
        _id: msg.sender._id, // 同时提供id和_id以兼容前端
        username: msg.sender.username,
        avatar: msg.sender.avatar
      },
      content: msg.content,
      type: msg.type,
      created_at: msg.createdAt,
      createdAt: msg.createdAt, // 同时提供created_at和createdAt以兼容前端
      updated_at: msg.updatedAt,
      updatedAt: msg.updatedAt // 同时提供updated_at和updatedAt以兼容前端
    }));

    return formattedMessages;
  } catch (error) {
    console.error('搜索群组消息失败:', error);
    throw error;
  }
};

// 标记群组消息为已读
const markGroupMessagesAsRead = async (groupId, userId) => {
  try {
    // 验证用户是否为群组成员
    const membership = await query(
      'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, userId]
    );

    if (membership.length === 0) {
      throw new Error('您不是该群组的成员，无法标记消息为已读');
    }

    // 标记用户未读的群组消息为已读
    const result = await Message.updateMany(
      {
        group_id: groupId,
        target_type: 'group',
        sender: { $ne: userId }, // 不包括自己发送的消息
        read_by: { $ne: userId } // 当前未标记为已读的
      },
      { $addToSet: { read_by: userId } }
    );

    console.log(`已将${result.modifiedCount}条群组消息标记为已读`);
    return result.modifiedCount;
  } catch (error) {
    console.error('标记群组消息已读失败:', error);
    throw error;
  }
};

module.exports = {
  sendGroupMessage,
  getGroupMessages,
  getGroupUnreadCount,
  getAllGroupsUnreadStatus,
  searchGroupMessages,
  markGroupMessagesAsRead
};